<?php

namespace App\Jobs;

use App\Jobs\Job;
use App\Models\AdminLog;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class SetAdminLog extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    private $userID;            //用户ID
    private $geoIP;             //geoIP信息
    private $event;             //事件名
    private $time;              //事件发生时间
    private $type;              //时间类型
    private $origin;            //事件发生前的数据
    private $ending;            //时间发生后的数据

    /**
     * 重建工作实例.
     * @param int       $userID 用户ID
     * @param array     $geoIP  geoIP
     * @param string    $event  事件名
     * @param timestamp $time   Carbon时间
     * @param string    $type   事件类型
     * @param json      $origin 事件发生前的数据
     * @param json      $ending 时间发生后的数据
     */
    public function __construct($userID, $geoIP, $event, $time, $type = 'Other', $origin = NULL, $ending = NULL)
    {
        $this->userID   =   $userID;
        $this->geoIP    =   $geoIP;
        $this->event    =   $event;
        $this->time     =   $time;
        $this->type     =   $type;
        $this->origin   =   $origin;
        $this->ending   =   $ending;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //写入数据库
        $createData = [
            'type'      =>      $this->type,
            'uid'       =>      $this->userID,
            'origin'    =>      $this->origin,
            'ending'    =>      $this->ending,
            'event'     =>      $this->event,
            'ip'        =>      $this->geoIP['ip'] ? $this->geoIP['ip'] : '未知',
            'iso_code'  =>      $this->geoIP['iso_code'] ? $this->geoIP['iso_code'] : '未知',
            'city'      =>      $this->geoIP['city'] ? $this->geoIP['city'] : '未知',
            'created_at'=>      $this->time,
            'updated_at'=>      $this->time
        ];
        AdminLog::create($createData);
    }
}
